#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>



void* create_thread(void* arg)
{
	int clientfd = *(int*)arg;
	char buffer[128] = {0};
	while(1)
	{
		ssize_t count = recv(clientfd, buffer, sizeof(buffer), 0);
		if(0 == count)
		{
			printf("disconnect\n");
			close(clientfd);
			return NULL;
		}
		printf("clientfd: %d, count: %ld, buffer: %s\n", clientfd, count, buffer);
		send(clientfd, buffer, count, 0);
	}
}


int main(int argc, char * * argv)
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == sockfd)
	{
		perror("socket:");
		exit(-1);
	}

	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(4396);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
	if(-1 == ret)
	{
		perror("bind:");
		exit(-1);
	}

	if(-1 == listen(sockfd, 10))
	{
		perror("listen:");
		close(sockfd);
		exit(-1);
	}

	while(1)
	{
		struct sockaddr_in client_addr;
		socklen_t len = sizeof(client_addr);
		int clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &len);
		if(-1 == clientfd)
		{
			perror("accept:");
			close(sockfd);
			exit(-1);
		}
		// 每接收到一个client就创建一个线程
		pthread_t ptid;
		pthread_create(&ptid, NULL, create_thread, &clientfd);
		
	}
	
	close(sockfd);
	
		
	exit(0);

}






